package org.example.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class TimeTaskService {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 执行定时输出时间的任务
     * @param duration 任务持续时间(秒)
     */
    public void executeTimePrintTask(int duration) {
        threadPoolExecutor.execute(() -> {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String threadName = Thread.currentThread().getName();

            for (int i = 0; i < duration; i++) {
                try {
                    Date now = new Date();
                    System.out.printf("[%s] %s - 当前时间: %s%n",
                            threadName, "定时任务", sdf.format(now));
                    Thread.sleep(1000); // 每1秒执行一次
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println(threadName + " 任务被中断");
                    break;
                }
            }
            System.out.println(threadName + " 定时任务执行完毕");
        });
    }

    /**
     * 执行倒计时任务
     * @param seconds 倒计时总秒数
     */
    public void executeCountdownTask(int seconds) {
        threadPoolExecutor.execute(() -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " 倒计时任务开始，总计 " + seconds + " 秒");

            for (int i = seconds; i > 0; i--) {
                try {
                    System.out.printf("[%s] 倒计时: %d 秒%n", threadName, i);
                    Thread.sleep(1000); // 每1秒执行一次
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println(threadName + " 倒计时任务被中断");
                    break;
                }
            }
            System.out.println(threadName + " 倒计时任务执行完毕");
        });
    }

    /**
     * 关闭线程池
     */
    public void shutdownThreadPool() {
        threadPoolExecutor.shutdown();
    }
}